<?php

namespace wx;

// 微信公众号 服务
class WxgzhService
{
    private $appid;
    private $appsecret;
    private $access_token;

    private $mchid;
    private $paykey;
    private $pay_notifyurl;

    public function __construct()
    {
        $this->appid = config('gzh_appid');
        $this->appsecret = config('gzh_secret');
        $this->access_token = $this->getAccessToken();
    }

    private function getAccessToken()
    {
        $accesstoken = cache('wxgzh_access_token');
        if ($accesstoken) {
            return $accesstoken;
        } else {
            $service_url = sprintf('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s', $this->appid, $this->appsecret);
            $result = HttpGet($service_url);
            $result = json_decode($result);
            if (isset($result->access_token) && strlen($result->access_token) > 10) {
                cache('wxgzh_access_token', $result->access_token, 3600);

                return $result->access_token;
            }
        }
    }

    // 获取用户信息
    public function getSubUserInfo($openid)
    {
        $service_url = sprintf('https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN', $this->access_token, $openid);
        $result = HttpGet($service_url);
        $result = json_decode($result, true);

        return $result;
    }

    //发送文本消息
    public function postTextEvent($postObj, $content)
    {
        $textTpl = '<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%d</CreateTime>
						<MsgType><![CDATA[text]]></MsgType>
						<Content><![CDATA[%s]]></Content>
					</xml>';
        if (!$content) {
            return '';
        }
        $resultStr = sprintf($textTpl, $postObj->FromUserName, $postObj->ToUserName, time(), $content);
        echo $resultStr;
    }

    //发送图文消息
    public function postNewsEvent($postObj, $items)
    {
        if (!$items || count($items) < 1) {
            return;
        }
        $newsTpl = '<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%d</CreateTime>
					<MsgType><![CDATA[news]]></MsgType>
					<ArticleCount>%d</ArticleCount>
					<Articles>%s</Articles>
					</xml>';
        $itemTpl = '<item>
					<Title><![CDATA[%s]]></Title> 
					<Description><![CDATA[%s]]></Description>
					<PicUrl><![CDATA[%s]]></PicUrl>
					<Url><![CDATA[%s]]></Url>
				</item>';
        $itemStr = '';
        foreach ($items as $v) {
            $itemStr .= sprintf($itemTpl, $v['title'], $v['description'], $v['picUrl'], $v['url']);
        }
        $resultStr = sprintf($newsTpl, $postObj->FromUserName, $postObj->ToUserName, time(), count($items), $itemStr);
        echo $resultStr;
    }

    // 公众号发送模板消息（加入消息队列）
    public function sendTemplateMsg($openid, $template_id, $data, $page = '', $time2wait = 0)
    {
        if ($time2wait==0) {
            $h = date("H");
            if ($h>22) {
                $time2wait = strtotime(date('Y-m-d 08:30:00', strtotime("+1 day"))) - time();
            }
            else if ($h<8) {
                $time2wait = strtotime(date('Y-m-d 08:30:00')) - time();
            }
        }
        $consumer = \app\sys\job\postQueue::class;
        $service_url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s';
        $para = [
            'touser' => $openid,
            'template_id' => $template_id,
            'data' => $data,
        ];
        if ($page) {
            $para['miniprogram'] = ['appid' => config('wx_appid'), 'pagepath' => $page];
        }
        $payload = ['ct' => time(), 'type' => '发送公众号模板消息', 'service_url' => $service_url, 'para' => $para];

        $queue = 'postQueue';
        $pushed = \think\Queue::later($time2wait, $consumer, $payload, $queue);
    }
    


}
